<?php
namespace Common\Service;

class PaymentService
{
    public $payment = null;
    public $error   = null;

    /**
     * 调用支付类型
     * @param  string $driver [description]
     * @return [type]         [description]
     */
    public function driver($driver = 'wechat')
    {
        $this->driver = $driver;
        switch ($driver) {
            case 'wechat':
                Vendor('Wechat.Payment');
                $this->payment = new \Payment(C("WX_CONF"));
                return $this;

            default:
                $this->payment = false;
                return $this;
        }
    }

    /**
     * app支付
     * @param  [type] $description [description]
     * @param  [type] $order_no    [description]
     * @param  [type] $total       [description]
     * @param  [type] $notify_url  [description]
     * @return [type]              [description]
     */
    public function app($description, $order_no, $total, $notify_url)
    {
        switch ($this->driver) {
            case 'wechat':
                return $this->wechatPay('', $description, $order_no, $total, $notify_url, 'APP');
                break;

            default:
                $this->error = '未找到' . $this->driver . '支付驱动';
                return false;
                break;
        }
    }

    protected function wechatPay($openid, $description, $order_no, $total, $notify_url, $method)
    {
        $result = $this->payment->get_prepay_id($openid, $description, $order_no, $total, $notify_url, $method);

        $prepay_id = '';
        if ($result['return_code'] == 'SUCCESS') {
            $prepay_id = $result['prepay_id'];
        } else {
            $this->error = $result['return_msg'];
            return false;
        }

        $package = $this->payment->get_package($prepay_id, 2);

        return $package;
    }
}
